package com.design.blog.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author hxg
 * @version 1.0
 * @date 2022/3/25 16:01
 */
@Component
@Aspect
@Slf4j
public class LogAop {
    @Pointcut("@annotation(com.design.blog.aop.LogAnno)")
    public void pt(){}

    @Around("pt()")
    public Object Log(ProceedingJoinPoint joinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        RecordLog(joinPoint, (end - begin));
        return result;
    }

    private void RecordLog(ProceedingJoinPoint joinPoint, long time) {
        //获取方法切点的标识信息
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnno annotation = method.getAnnotation(LogAnno.class);
        //获取注解参数
        String module = annotation.module();
        String operator = annotation.operator();
        log.info("==============log-start================");
        log.info("request模块：{}",module);
        log.info("request方法：{}",operator);
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method{}",className+"."+methodName+"()");
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("request参数：{}",params);
        log.info("request时长：{}毫秒", time);
        log.info("=============log-end===================");

    }

}
